import { debounce } from '@/utils/common';
import { onMounted, onActivated, onBeforeUnmount, onDeactivated, ref } from 'vue';
export function resizeMixins(chart: Record<string, any>) {
	const $_sidebarElm = ref<Element>();
	const $_resizeHandler = ref<() => void>();
	onMounted(() => {
		console.log('mixinMounted--', window);
	});
	onActivated(() => {
		initListener();
		resize();
	});
	onBeforeUnmount(() => {});
	onDeactivated(() => {
		destroyListener();
	});

	// use $_ for mixins properties
	// https://vuejs.org/v2/style-guide/index.html#Private-property-names-essential
	function $_sidebarResizeHandler(e: Record<string, any>) {
		if (e.propertyName === 'width') {
			$_resizeHandler.value!();
		}
	}
	function initListener() {
		$_resizeHandler.value = debounce(() => {
			resize();
		}, 100);
		window.addEventListener('resize', $_resizeHandler.value!);
		$_sidebarElm.value = document.getElementsByClassName('sidebar-container')[0];
		$_sidebarElm.value && $_sidebarElm.value.addEventListener('transitionend', $_sidebarResizeHandler);
	}
	function destroyListener() {
		window.removeEventListener('resize', $_resizeHandler.value!);
		$_resizeHandler.value = undefined;
		$_sidebarElm.value && $_sidebarElm.value.removeEventListener('transitionend', $_sidebarResizeHandler);
	}
	function resize() {
		if (chart) {
			if (chart.constructor === Object) {
				for (const c in chart) {
					chart[c] &&
						chart[c].resize({
							width: chart[c]._dom.clientWidth,
						});
				}
			} else {
				chart && chart.resize();
			}
		}
	}
}
